package cn.itcast.tlias.com.tliaswork.intercepter;

import cn.itcast.tlias.com.tliaswork.pojo.Result;
import cn.itcast.tlias.com.tliaswork.utils.JWTUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckIntercept implements HandlerInterceptor {

    //目标资源方法执行前执行    ,放行返回ture,不放行返回false
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle....");
        String uri = request.getRequestURL().toString();
        if (uri.contains("login")) {
            log.info("登录操作放行");
            //2.1.放行
            return true;
        }
        //3,获取token令牌
        String token = request.getHeader("token");
        //4,判断token令牌是否是否存在
        if (TextUtils.isEmpty(token)) {
            log.info("请求头的token,返回未登录的类型");
            Result error = Result.error("NOT_LOGIN");
            //手动的转换
            String errorJson = JSONObject.toJSONString(error);

            //设置中文不乱吗
            response.setContentType("text/html;charset=utf-8");
            //返回中文字符串
            response.getWriter().write(errorJson);
            return false;
        } else {
            log.info("请求头的token有值");
            //5解析token值,如果解析失败,返回错误结果
            boolean expire = JWTUtils.isExpire(token);
            if (expire) {
                //6,放行
                return true;
            } else {
                //如果令牌出错也需要返回错误信息
                Result error = Result.error("NOT_LOGIN");
                //手动的转换
                String errorJson = JSONObject.toJSONString(error);

                //设置中文不乱吗
                response.setContentType("text/html;charset=utf-8");
                //返回中文字符串
                response.getWriter().write(errorJson);
                return false;
            }
        }


    }

    //目标方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        log.info("postHandle....");
    }

    //视图渲染完毕后执行,最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("afterCompletion....");
    }
}
